# -*- coding: utf8

import sys, logging, logging.handlers

class Log(object):
    """Logger class"""
   
    def __init__(self, log_file, logger_name, maxb, count, debug):
        try:
            fmt = '%(asctime)s: %(name)s: %(levelname)s: %(message)s'
            datefmt = '%a, %d %b %Y %H:%M:%S'
            self.logger = logging.getLogger(logger_name)
            self.logger.setLevel(logging.INFO)
            self.handler = logging.handlers.RotatingFileHandler(
                      log_file, maxBytes=maxb, backupCount=count) 
            formatter = logging.Formatter(fmt, datefmt)
            self.handler.setFormatter(formatter)                
            self.logger.addHandler(self.handler)
            if debug:
                self.logger.addHandler(logging.StreamHandler(sys.stdout))
            self.levels = {'debug': self.logger.debug,
                      'info': self.logger.info,
                      'warning': self.logger.warning,
                      'error': self.logger.error,
                      'critical': self.logger.critical}
        except IOError as err:
            print "cannot open log file %s" % err
            sys.exit(1)

    def log(self, message, level):
        """Log message"""
        self.levels[level](message)

    def close(self):
        """Close logging"""
        self.handler.close()
        logging.shutdown()
